<?php
/*
v1.00
Bach
2017-01-13
*/
namespace app\common\model;
// use think\Model;

class Wechat {
    
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------

    private $appId;
    private $appSecret;
    private $appName;

    private $access_token = null;
    private $jsapi_ticket = null;

    public function __construct() {
        $account = config('wechat');
        $this->appId = $account['APPID'];
        $this->appSecret = $account['APPSECRET'];
        $this->appName = $account['APPNAME'];
        $this->access_token = $this->getAccessToken();
    }
    private function getJsApiTicket() {
        $file_path = "../application/".$this->appName."/jsapi_ticket.json";
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->getJson($file_path));
        $expire_time = isset($data->expire_time)?$data->expire_time:0;
        if ($expire_time < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $this->setJson($file_path, json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }
    public function getAccessToken() {
        if($this->access_token) return $this->access_token;
        $file_path = "../application/".$this->appName."/access_token.json";
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->getJson($file_path));
        $expire_time = isset($data->expire_time)?$data->expire_time:0;
        if ($expire_time < time()) {
            // dump('start');
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode(httpGet($url));
//            $res = json_decode(file_get_contents($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $this->setJson($file_path, json_encode($data));
            }
        } else {
            $access_token = $data->access_token;
        }
        $this->access_token = $access_token;
        return $access_token;
    }
    //激活服务器链接 一次性函数(微信验证token)
    public function valid() {
        if ($this->checkSignature()) {
            if ($_SERVER['REQUEST_METHOD'] == 'GET') {
                echo $_GET['echostr'];
                exit;
            }
        } else {
            $this->write_log('认证失败');
            exit;
        }
    }
    private function checkSignature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmpArr = array(C(WECHATTOKEN), $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
    //微信网页开发jsapi所需的验证参数
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url = input('url');
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
                //还要添加需要使用的JS接口列表 jsApiList: ['chooseImage','uploadImage']
        );
        return $signPackage;
    }
    //辅助功能
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
    public function httpPost($url, $data) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
    public function getJson($filename) {
        return trim(file_get_contents($filename));
    }
    private function setJson($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, $content);
        fclose($fp);
    }
    //业务功能
    //业务功能
    //业务功能

    //发送通知消息
    public function notice($demand, $data) {
        //check demand
        $config = getConfig('wechat.notice',1);
        if(!$config) return array(errormsg=>'wechat message config error');
        $config = $config[$demand];
        if(!$config) return array(errormsg=>'wechat message demand error');
        //check openid
        $openid = $data['openid'];
        if(!$openid) return array(errormsg=>'wechat message need openid');
        $post[touser] = $openid;
        foreach ($config[need] as $key => $wx) {
            $c = $data[$key];
            if(!$c) return array(errormsg=>"wechat message need $key");
            $wxk = explode(",",$wx);
            $post[data][$wxk[0]][value] = $c;
            if($wxk[1]) $post[data][$wxk[0]][color] = $wxk[1];
        }
        if(isEn()) $template_id = $config[template_id_en];
        if(!$template_id) $template_id = $config[template_id];
        if(!$template_id) return array(errormsg=>'template_id missing');
        $post[template_id] = $template_id;
        $url = $data[url];
        if($url) $post[url] = $url;
        $post = json_encode($post);
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $res = httpPost($url, $post);
        $ret = json_decode($res, true);
        if($ret[errmsg] != 'ok') return array(errormsg=>$ret[errmsg]);
        return array(state=>1);
    }
    //用户标签
    public  function tag_user_remove($tag,$openid){
        return;
        return $this->tag_user_set($openid,$tag,0);
    }
    public  function tag_user_add($tag,$openid){
        return;
        return $this->tag_user_set($openid,$tag,1);
    }
    private function tag_user_set($openid,$tag,$isAdd){
        if(!$openid) return array('errormsg'=>'wechat tag openid missing');
        $tag_id = $this->tag_get_id($tag);
        if(!$tag_id){
            return array('errormsg'=>'wechat tag_id missing');
        }
        $access_token = $this->access_token;
        if($isAdd){
            $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=$access_token";
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=$access_token";
        }
        if(!is_array($openid)) $openid = array($openid);
        $data = array(
          "openid_list" => $openid,
          "tagid" => $tag_id
        );
        $ret = $this->httpPost($url,json_encode($data));
        $ret = json_decode($ret,1);
        if(!isset($ret['errmsg']) || $ret['errmsg'] != 'ok') return array('errormsg'=>$ret['errmsg']);
        return array('state'=>1);
    }
    private function tag_get_id($tag){
        $tags = $this->tag_get_info();
        $tags = isset($tags['tags'])?$tags['tags']:[];
        foreach($tags as $i => $a){
            if($a['name'] == $tag){
                return $a['id'];
            }
        }
        cache('wechat.tags',null);
        $data = array('tag'=>array('name'=>$tag));
        $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=$this->access_token";
        $res = $this->httpPost($url,json_encode($data));
        $res = json_decode($res,1);
        return $res['tag']['id'];
    }
    private $tags;
    private function tag_get_info(){//array
        if($this->tags){return $this->tags;}
        $this->tags = $tags = cache('wechat.tags');
        if($tags) return $tags;
        $access_token = $this->access_token;
        $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=$access_token";
        $ret = $this->httpGet($url);
        $ret = json_decode($ret, true);
        $this->tags = $tags = $ret;
        return $tags;
    }

}
